<template>
  <el-dialog :visible.sync="visible" width="800px" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" @open="open" @close="close" :append-to-body="true" :modal-append-to-body="true">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="100px" :disabled="disableEditSubmit">
      <el-row v-if="isFromMenu">
        <el-col :span="12">
          <el-form-item label="所属会议" prop="meetId" :rules="rules.validateRequire">
            <el-input v-model="model.meetName" :disabled="true" class="tl-ref-selector">
              <el-button slot="append" type="primary" icon="el-icon-search" @click="openMeetManageRefDialog"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="发起日期" prop="initiatedate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.initiatedate" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务分类" prop="category" :rules="rules.validateRequire">
            <el-select v-model="model.category" filterable clearable>
              <el-option v-for="item in codeModelFromOA.taskCategoryList" :key="'category' + item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
            <el-col :span="24">
              <el-form-item label="责任人">
                <tl-ref-mulit-user-select v-model="users" :disabled="disableEditSubmit"></tl-ref-mulit-user-select>
              </el-form-item>
            </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="时间要求" prop="daterequirement" :rules="rules.validateRequire">
            <el-select v-model="model.daterequirement" filterable clearable>
              <el-option v-for="item in codeModelFromOA.dateRequirementList" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="model.daterequirement === '1'">
          <el-form-item label="截止日期" prop="enddate" :rules="model.daterequirement === '1' ? rules.validateRequire : { required: 'false' }">
            <el-date-picker v-model="model.enddate" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务主题" prop="taskmaintitle" :rules="rules.validateRequire">
            <el-input v-model="model.taskmaintitle"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务内容" prop="taskdescription" :rules="rules.validateRequire">
            <el-input v-model="model.taskdescription" type="textarea" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="text" @click="doSubmitDraft" :loading="saveLoading" v-if="disableEditSubmit === false">保存</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="disableEditSubmit === false">发布</el-button>
    </div>
    <tl-ref-meet-manage ref="meetManageRef" :singleSelect="true" @confirm="getMeetManageRefData" :externalSelectedRowKeys="'model.meetId'"></tl-ref-meet-manage>
    <tl-ref-team ref="teamRef" :singleSelect="true" @confirm="getTeamRefData" :externalSelectedRowKeys="'model.handleteamids'"></tl-ref-team>
  </el-dialog>
</template>
<script>
/** mixins */
import { mixin_edit } from "@tapui/mixins/mixin_edit"
/** 子组件 */
import tlRefMeetManage from "../meetManage/refList"
import tlRefTeam from "../../base/baseTeamInfo/refList"
import tlRefMulitUserSelect from '@/components/common/refMulitUserSelect'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from "@tapui/utils/http"
import axios from "axios"
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { tlRefMeetManage, tlRefTeam, tlRefMulitUserSelect },
  data() {
    return {
      moduleTitle: "任务组",
      urlPrefix: "/meet/taskMaster/",
      activeTab: "basic",
      url: {
        // 额外的url
        queryCodeList: "",
        confirmChooseUsers: "/meet/taskMaster/confirmChooseUsers"
      },
      users: {
        usernames: '',
        usercodes: '',
        deptnames: '',
        deptcodes: '',
        teamids: '',
        teamnames: '',
        roleids: '',
        rolenames: ''
      }
    }
  },
  props: {
    // 是否是从菜单页面进入的
    isFromMenu: {
      type: Boolean,
      default: true
    },
    codeModelFromOA: {
      type: Object,
      default: function() {
        return {}
      }
    },
    sourceMeetID: {
      type: [Number, String],
      default: ""
    }
  },
  methods: {
    loaded() {
      // 页面加载完毕执行
      if (!this.isFromMenu && this.isAdd) {
        this.model.meetid = this.sourceMeetID
        this.users = {
          usernames: '',
          usercodes: '',
          deptnames: '',
          deptcodes: '',
          teamids: '',
          teamnames: '',
          roleids: '',
          rolenames: ''
        }
      } else {
        this.initHandleUserInfo()
      }
      // 如果任务类型只有一项，则默认赋值选中
      let taskCategoryList = this.codeModelFromOA.taskCategoryList
      if (taskCategoryList.length === 1) {
        this.$set(this.model, "category", taskCategoryList[0].code)
      }
    },
    /** confirmInitiator(selectedData) {
      const { code, name } = selectedData[0]
      this.$set(this.model, "usercode", code)
      this.$set(this.model, "username", name)
    },*/
    /** 打开会议管理参照 */
    openMeetManageRefDialog() {
      this.$refs.meetManageRef.visible = true
    },
    /** 获取会议管理参数数据 */
    getMeetManageRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, "meetId", selectionRow.id)
      this.$set(this.model, "meetName", selectionRow.name)
    },
    /** 打开团队参照 */
    openTeamRefDialog() {
      this.$refs.teamRef.visible = true
    },
    /** 获取团队数据 */
    getTeamRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, "handleteamids", selectionRow.id)
      this.$set(this.model, "handleteamnames", selectionRow.name)
    },
    /** 提交前执行 */
    async beforeSubmit() {
      // 判断是否选择责任人
      if (this.users.usercodes.length === 0 && this.users.deptcodes.length === 0 && this.users.teamids.length === 0 && this.users.roleids.length === 0) {
        this.$tap.alert("责任人必须填写", "warning")
        return false
      }
      // 将选择责任用户的值绑定到model上
      this.bindUserValue()

      const { handleroleids, handledeptcodes, handleteamids, handleusercodes, handleusernames } = this.model
      const param = { handleroleids, handledeptcodes, handleteamids, handleusercodes, handleusernames }
      return await getAction(this.url.confirmChooseUsers, param)
        .then((res) => {
          if (res.success) {
            if (!res.result.isHaveUser) {
              this.$tap.alert("选择的责任人中无有效用户，请重新选择", "warning")
              return false
            } else if (!res.result.isLegalCount) {
              return this.$tap
                .confirm("选择的人员已经超过" + res.result.taskMaxBatchSize + "人，确定要创建吗？")
                .then((_) => {
                  return true
                })
                .catch((_) => {
                  return false
                })
            } else {
              return true
            }
          } else {
            this.$tap.alert(res.message, "warning")
          }
          return false
        })
        .catch((err) => {
          this.$tap.alert("系统发生错误，请联系系统管理员", "error")
          return false
        })
    },
    // 初始化发起人和记录人信息
    initPersonInfo() {
      let loginUserCode = this.$store.getters.user.code
      let loginUserName = this.$store.getters.user.name
      // 发起人信息
      this.$set(this.model, "initiatorcode", loginUserCode)
      this.$set(this.model, "initiatorname", loginUserName)
      // 记录人信息
      this.$set(this.model, "usercode", loginUserCode)
      this.$set(this.model, "username", loginUserName)
    },
    /** 保存确认 */
    async doSubmitEdit() {
      if (!(await this.beforeSubmit())) {
        return
      }
       this.$tap.confirm('确定发布吗？发布后不可修改！(注：发布可能有一定时间的延迟)').then((_) => {
           this.initPersonInfo()
        this.$refs.form.validate((valid) => {
            if (valid) {
            this.$set(this.model, "state", 2)
            if (this.isAdd) {
                this.doAdd()
            } else {
                this.doEdit()
            }
            } else {
            return false
            }
        })
      })
    },
    /** 草稿确认 */
    async doSubmitDraft() {
      if (!(await this.beforeSubmit())) {
        return
      }
      this.initPersonInfo()
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$set(this.model, "state", 1)
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        } else {
          return false
        }
      })
    },
    // 将选择用户值绑定到model上
    bindUserValue() {
      this.$set(this.model, "handleroleids", this.users.roleids)
      this.$set(this.model, "handlerolenames", this.users.rolenames)
      this.$set(this.model, "handledeptcodes", this.users.deptcodes)
      this.$set(this.model, "handledeptnames", this.users.deptnames)
      this.$set(this.model, "handleteamids", this.users.teamids)
      this.$set(this.model, "handleteamnames", this.users.teamnames)
      this.$set(this.model, "handleusercodes", this.users.usercodes)
      this.$set(this.model, "handleusernames", this.users.usernames)
    },
    // 将model值赋值给this.user
    initHandleUserInfo() {
      if (this.model.handleroleids) {
        this.$set(this.users, "roleids", this.model.handleroleids)
        this.$set(this.users, "rolenames", this.model.handlerolenames)
      }
      if (this.model.handledeptcodes) {
        this.$set(this.users, "deptcodes", this.model.handledeptcodes)
        this.$set(this.users, "deptnames", this.model.handledeptnames)
      }
      if (this.model.handleteamids) {
        this.$set(this.users, "teamids", this.model.handleteamids)
        this.$set(this.users, "teamnames", this.model.handleteamnames)
      }
      if (this.model.handleusercodes) {
        this.$set(this.users, "usercodes", this.model.handleusercodes)
        this.$set(this.users, "usernames", this.model.handleusernames)
      }
    }
  }
}
</script>
